const jwt = require('jsonwebtoken')

const errorType = require('../constants/error_types')
const service = require('../service/user_service')
const authService = require('../service/auth_service')
const md5password = require('../utils/password_handle')
const {PUBLIC_KEY} = require('../app/config')

// 登录时的判断
const verifyLogin = async(ctx,next)=>{
  const {name,password} = ctx.request.body

  // 用户名或密码是否为空
  if(!name || !password){
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_EMP)
    return ctx.app.emit('error',error,ctx)
  }

  // 用户是否存在
  const user = (await service.getUserByName(name))[0]
  if(!user){
    const error = new Error(errorType.NAME_NOT_EXIST)
    return ctx.app.emit('error',error,ctx)
  }

  // 判断密码是否正确
  if(md5password(password) != user.password){
    const error = new Error(errorType.PASSWORD_IS_ERROR)
    return ctx.app.emit('error',error,ctx)
  }

  ctx.user = user

  await next()
}

// 验证是否有token
const verifyAuth = async(ctx,next)=>{
  // 获取token
  const authorization = ctx.headers.authorization
  if(!authorization){
    const error = new Error(errorType.UNAUTHORIZATION)
    return ctx.app.emit('error',error,ctx)
  }
  const token = authorization.replace('Bearer ','')

  // 验证token
  try{
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms:['RS256']
    })
    ctx.user = result
    await next()
  }catch(err){
    const error = new Error(errorType.UNAUTHORIZATION)
    ctx.app.emit('error',error,ctx)
  }
}

// 当前用户是否拥有权限
const verifyPermission = (tableName,router_id)=>{
  return async(ctx,next)=>{
    let momentId = ctx.params.momentId
    // 上传动态图片时
    if(router_id == 'true'){
      momentId = ctx.query.momentId
    }
    const {id} = ctx.user
  
    const isPermission = await authService.checkResource(tableName,momentId,id)
    
    if(!isPermission){
      const error = new Error(errorType.UNPERMISSION)
      return ctx.app.emit('error',error,ctx)
    }
    await next()
  }
}

module.exports = {
  verifyLogin,
  verifyAuth,
  verifyPermission
}